package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;


    /**
     * token解析
     *
     * @param response
     * @param 解析Token失败
     */
    private static void tokenParseFail(HttpServletResponse response, String 解析Token失败) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        throw new BaseException(解析Token失败);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("authorization");
        //2.判断token是否存在，不存在直接返回401
        if (ObjectUtil.isEmpty(token)) {
            tokenParseFail(response, "用户未登录");
        }

        //3.解析token，如果解析失败直接返回401
        Claims claims = tokenService.parseToken(token);
        if (ObjectUtil.isEmpty(claims)) {
            tokenParseFail(response, "解析Token失败");
        }

        //4.从token获取用户信息(userId)，如果获取不到直接返回401
//        Long userId = (Long) claims.get("userId");
        Long userId = MapUtil.getLong(claims, "userId");
        if (ObjectUtil.isEmpty(userId)) {
            tokenParseFail(response, "认证失败");
        }

        //5.如果用户信息存在，将用户信息存入ThreadLocal
        UserThreadLocal.set(userId);
        //6.放行
        return true;


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除ThreadLocal中的数据
        UserThreadLocal.remove();


    }

}
